package acom.dhy.qigsaw2test.qigsaw

import acom.dhy.qigsaw2test.App
import acom.dhy.qigsaw2test.App.Companion.testCases
import android.app.Activity
import android.app.AlertDialog
import com.dhy.annotations.Components
import com.dhy.qigsaw.splash.data.TestCase
import com.dhy.xintent.toast
import com.iqiyi.android.qigsaw.core.Qigsaw
import java.nio.charset.Charset

enum class DynamicFeature(vararg names: String, val onActivityResult: (Activity) -> Unit) {
    JAVA("java", onActivityResult = {
        it.startActivityComponent(Components.Java.JAVA_SAMPLE_ACTIVITY)
    }),
    ASSETS("assets", onActivityResult = {
        it.displayAssets()
    }),
    NATIVE("native", onActivityResult = {
        it.startActivityComponent(Components.Native.NATIVE_SAMPLE_ACTIVITY)
    }),
    ALL("java", "assets", "native", onActivityResult = {
        it.toast("all installed")
    });

    val moduleNames = names.toList()

    companion object {
        fun find(moduleNames: List<String>): DynamicFeature? {
            return values().find { it.moduleNames == moduleNames }
        }
    }
}

fun Activity.displayAssets() {
    try {
        val inputStream = assets.open("assets.txt")
        val txt = inputStream.readBytes().toString(Charset.defaultCharset())
        inputStream.close()
        testCases[TestCase.ASSETS] = true
        val dialog = AlertDialog.Builder(this)
            .setTitle("Asset Content")
            .setMessage(txt)
            .show()
        if (App.AUTO_TEST_MODE) window.decorView.postDelayed({ dialog.dismiss() }, 200)
    } catch (e: Exception) {
        testCases[TestCase.ASSETS] = false
        e.printStackTrace()
    }
}

/**
 * 如果新下载的是资源类插件，需要先注入，然后当前页面才能访问。
 * */
fun Activity.injectNewResource() {
    Qigsaw.onApplicationGetResources(resources)
}